<?php 
require_once dirname(dirname(__FILE__)) .'/cse-init.php';

// authentication is required!
Cinnamon::registry('session')->applyAuthenticationPolicy();

// load required classes
Cinnamon::loadClass('Container');
Cinnamon::loadClass('DataGrid');
Cinnamon::loadClass('Text');
Cinnamon::loadClass('URLConnection');

// fetch required object from registry
$view = Cinnamon::registry('view');
$db = Cinnamon::registry('db');

// Spy DataGrid
$container = new Container('Spy');
$spy = new DataGrid();
$container->addChild($spy);
$spy->addColumn('Resource', 'function', 'spyResourceLabel', 'format', 'nowrap');
$spy->addColumn('Time', 'field', 'request_datetime', 'format', 'time');
$spy->addColumn('IP', 'field', 'ip_address', 'format', 'ip');
$spy->addColumn('Country', 'function', 'spyCountryLabel', 'format', 'country');

$dp = $db->requests('request_url, request_title, ip_address, request_datetime')
		 ->sort('request_datetime', 'DESC')
		 ->slice(0, 15);
if ( Cinnamon::inMode('ajax') ) {
	$dp->filter('request_utc_datetime > \''. $db->getDatetime( time() - 5 ) .'\'');
} else {
	$dp->filter('request_utc_datetime > \''. $db->getDatetime(time() - ( 15 *  SECS_PER_MIN )) .'\'');
}
$spy->setDataProvider($dp);
$view->addChild($container);

function spyResourceLabel($item) {
	$title = nvl($item->request_title, $item->request_url);
	return '<a href="'. $item->request_url .'" title="'. $title .'">'. $title .'</a>';
}

function spyCountryLabel($item) {
	// Uses free service from hostip.info
	$u = new URLConnection("http://api.hostip.info/country.php?ip=".$item->ip_address);
	return $u->getContents();
}

// attach spy.js
function spyOnHead($event) {
	echo '<script type="text/javascript" src="'. CSEURL .'/view/scripts/spy.js"></script>';
}
Cinnamon::registry('events')->addEventListener('head', 'spyOnHead');

// render output
$view->render();
?>